package com.zhengtoudai.ui.fragment;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.zhengtoudai.R;
import com.zhengtoudai.base.App;
import com.zhengtoudai.base.BaseFragment;
import com.zhengtoudai.global.Config;
import com.zhengtoudai.http.HttpUtil;
import com.zhengtoudai.injector.component.DaggerActivityComponent;
import com.zhengtoudai.injector.module.ActivityModule;
import com.zhengtoudai.ui.activity.InvestmentActivity;
import com.zhengtoudai.ui.activity.LoginActivity;
import com.zhengtoudai.ui.activity.WebViewActivity;
import com.zhengtoudai.ui.bean.Index;
import com.zhengtoudai.ui.bean.Result;
import com.zhengtoudai.ui.presenter.IndexPresenterImpl;
import com.zhengtoudai.ui.presenter.LoginOutPresenterImpl;
import com.zhengtoudai.ui.view.CommonView;
import com.zhengtoudai.ui.view.IndexView;
import com.zhengtoudai.util.AbToastUtil;
import com.zhengtoudai.util.DensityUtil;
import com.zhengtoudai.view.WaveHelper;
import com.zhengtoudai.view.WaveView;
import com.zhengtoudai.view.banner.ConvenientBanner;
import com.zhengtoudai.view.banner.NetworkImageHolderView;
import com.zhengtoudai.view.banner.holder.CBViewHolderCreator;
import com.zhengtoudai.view.banner.listener.OnItemClickListener;
import com.zhengtoudai.view.swipetoloadlayout.base.OnRefreshListener;
import com.zhengtoudai.view.swipetoloadlayout.base.SwipeToLoadLayout;

import java.util.ArrayList;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 作者：黑哥 on 2016/7/28 15:56
 */
public class HomeFragment extends BaseFragment implements OnItemClickListener, View.OnClickListener, CommonView, IndexView {


    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    @Bind(R.id.waterWaveView)
    WaveView mWaterWaveView;

    @Bind(R.id.fragment_home_convenient_banner)
    ConvenientBanner convenientBanner;
    @Bind(R.id.tv_notice)
    TextView mTvNotice;
    @Bind(R.id.tv_project_title)
    TextView mTvProjectTitle;

    @Bind(R.id.tv_content_label)
    TextView mTvContentLabel;
    @Bind(R.id.tv_investment)
    TextView mTvInvestment;
    @Bind(R.id.swipe_target)
    ScrollView mSwipeTarget;
    @Bind(R.id.ll_notice)
    LinearLayout mLlNotice;
    private View view;

    private ArrayList<String> localImages = new ArrayList<String>();

    private WaveHelper mWaveHelper;
    private int mBorderColor = Color.parseColor("#ffbbc4");
    private int mBorderWidth = 3;

    private String[] bannerUrls;

    @Inject
    LoginOutPresenterImpl mPresenter;

    @Inject
    IndexPresenterImpl mIndexPresenter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        super.onCreateView(inflater, container, savedInstanceState);
        return view;
    }

    @Override
    protected void initTitle() {
        String rightTitle;
        if (App.mApp.hasLogin()) {
            rightTitle = "退出";
        } else {
            rightTitle = "登陆";
        }
        titleUtil.setTitleImgOrRight(R.mipmap.logo, rightTitle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (App.mApp.hasLogin()) {
                    showAlertDialog("是否退出登录", "取消", "退出", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mPresenter.loginOut();
                        }
                    });
                } else {
                    startActivity(LoginActivity.class);
                }

            }
        });
    }

    @Override
    protected void initView() {
        mWaterWaveView.setBorder(DensityUtil.dip2px(mContext,mBorderWidth), mBorderColor);

        mWaveHelper = new WaveHelper(mWaterWaveView);
//        mWaterWaveView.setWaveColor(
//                Color.parseColor("#40b7d28d"),
//                Color.parseColor("#80b7d28d"));
//        mBorderColor = Color.parseColor("#B0b7d28d");

        mWaveHelper.start();

        DaggerActivityComponent.builder().appComponent(App.mApp.getAppComponent())
                .activityModule(new ActivityModule(getActivity()))
                .build()
                .inject(this);
        mPresenter.attachView(this);
        mIndexPresenter.attachView(this);
        convenientBanner = (ConvenientBanner) view.findViewById(R.id.fragment_home_convenient_banner);
        mRefresh.setLoadMoreEnabled(false);
        mRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mIndexPresenter.getIndexBorrow();
            }
        });


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
        mIndexPresenter.detachView();
    }

    @Override
    protected void setData() {
        mIndexPresenter.getIndexBorrow();

    }


    private void initBanner() {
        if (localImages != null && localImages.size() > 0) {
            localImages.clear();
        }
        for (int i = 0; i < bannerUrls.length; i++) {
            localImages.add(Config.URL+bannerUrls[i]);
            Log.e("TAG", "添加图片="+ Config.BASE_URL+ bannerUrls[i]);
        }
        convenientBanner.setPages(
                new CBViewHolderCreator<NetworkImageHolderView>() {
                    @Override
                    public NetworkImageHolderView createHolder() {
                        return new NetworkImageHolderView();
                    }
                }, localImages)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.ic_normal_circle, R.mipmap.ic_select_circle})
                //指示器圆点位置，默认居中
//                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                .setOnItemClickListener(this);
//        convenientBanner.setManualPageable(false);//设置不能手动影响

    }


    // 开始自动翻页
    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
        if (localImages.size() > 1) {
            convenientBanner.startTurning(3000);
        }
        initTitle();
    }

    // 停止自动翻页
    @Override
    public void onPause() {
        super.onPause();
        //停止翻页
        convenientBanner.stopTurning();
    }


    @Override
    public void onItemClick(int position) {
        //图片轮播点击事件
//        Tool.showTextToast(getActivity(),"点击了第"+position+"个");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.ll_notice, R.id.tv_investment})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_notice:

                break;
            case R.id.tv_investment:

                break;
        }
    }


    @Override
    public void showDialog() {
        showProgressDialog("正在退出中...");
    }

    @Override
    public void onResult(Result result) {
        if (result.getCode() == Config.SUCCESSFUL_CODE) {
            startActivity(LoginActivity.class);
            App.mApp.logout();
        }
        AbToastUtil.showToast(mContext, result.getMessage());
    }


    @Override
    public void dismissDialog() {
        dismissProgressDialog();
    }

    @Override
    public void onFailure(Throwable e) {
        HttpUtil.disposeOnFailure(mContext, e);
    }

    @Override
    public void showIndexDialog() {
        showProgressDialog("正在加载中...");
    }

    @Override
    public void onIndexFailure(Throwable e) {
        HttpUtil.disposeOnFailure(mContext, e);
    }


    @Override
    public void onIndexResult(final Index result) {
        bannerUrls = new String[result.getContentListPic().size()];
        for (int i = 0; i < bannerUrls.length; i++) {
            bannerUrls[i] = result.getContentListPic().get(i).getAttach_path();
        }
        initBanner();
        if (result.getBorrowInfo()!=null&&result.getBorrowInfo().size()>0){
            mTvProjectTitle.setText(result.getBorrowInfo().get(0).getBorrowTitle());
            mWaterWaveView.setProgressRatie(result.getBorrowInfo().get(0).getRate()+"%");
            Log.e("progress",result.getBorrowInfo().get(0).getTenderProgressRate()/100+"");
            mWaterWaveView.setProgress(result.getBorrowInfo().get(0).getTenderProgressRate()/100);
            //mWaterWaveView.setWaterLevelRatio(result.getBorrowInfo().get(0).getTenderProgressRate()/100);
            if (Build.VERSION.SDK_INT<Build.VERSION_CODES.JELLY_BEAN){
                mTvInvestment.setBackgroundDrawable(ContextCompat.getDrawable(mContext,R.drawable.shape_red_button));
            }else{
                mTvInvestment.setBackground(ContextCompat.getDrawable(mContext,R.drawable.shape_red_button));
            }
            mTvInvestment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle=new Bundle();
                    bundle.putString("borrowEId",result.getEid());
                    startActivity(bundle,InvestmentActivity.class);
                }
            });
            mWaterWaveView.setDeadline(result.getBorrowInfo().get(0).getBorrowTimeLimit()+result.getBorrowInfo().get(0).getIsDay());

        }

        mTvNotice.setText(result.getContentTitle().getContent_title());
        mLlNotice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String html="<!DOCTYPE HTML><html><body>" +result.getContentTitle().getContent_txt()+ "</body></html>";
                Bundle bundle=new Bundle();
                bundle.putString("title","公告");
                bundle.putString("html",html);
                startActivity(bundle, WebViewActivity.class);
            }
        });
        App.mApp.getSession().set("customPhone",result.getCustomPhone());
        App.mApp.getSession().set("weChatCode",result.getWeChatCode());


    }

    @Override
    public void dismissIndexDialog() {
        dismissProgressDialog();
        if (mRefresh.isRefreshing()){
            mRefresh.setRefreshing(false);
        }
    }

}

